using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.RolePermissions.Interfaces;
using Identity.Application.Roles.Commands;
using Identity.Domain.Aggregates;
using MediatR;
using Microsoft.VisualBasic;

namespace Identity.Application.Roles.CommandHandlers
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, Result>
    {
        private IRoleService _roleService;
        private IRolePermissionsReadService _rolePermissionsReadService;

        public UpdateRoleCommandHandler(IRoleService roleService, IRolePermissionsReadService rolePermissionsReadService)
        {
            _roleService = roleService;
            _rolePermissionsReadService = rolePermissionsReadService;
        }
        public async Task<Result> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            var roleData = await _roleService.GetRoleByIdAsync(request.roleId);

            if (roleData == null) return Result.Failure("角色不存在");

            var role = Role.LoadFromPersistence(roleData.Id, roleData.Code, roleData.Name,roleData.PermissionIds,roleData.Description,roleData.Status);

            role.ChangeName(request.roleName);
            role.ChangeCode(request.roleCode);
            role.ChangeDescription(request.description);      

            var result = await _roleService.SaveRoleAsync(role);
            if (result == null) return Result.Failure("更新失败");

            return Result.Success(result);

        }
    }
}